const express = require('express');
const router = express.Router();
const examine_scores_Model = require('../models/examine_scores_model');
// const view_Model = require('../models/view_model');
 
// 获取所有用户成绩信息
router.get('/all_exam_scores', async (req, res) => {
  try {
    const examine_scores = await examine_scores_Model.getAll_scores();
    // console.log('获取到的全部用户数据：',examine_scores)
    for(let i=0;i<examine_scores.length;i++){
      // console.log('全部用户时间数据：',examine_scores[i].exam_date)
      const date = new Date(examine_scores[i].exam_date);
      const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
      examine_scores[i].exam_date = formattedDate
      // console.log('全部用户时间数据：',examine_scores[i].exam_date)
    }
    res.json(examine_scores);
  } catch (err) {
    console.error(err);
    res.status(500).send('获取全部成绩信息错误-Error');
  }
  // res.json({ message: 'all_exam_scores获取成功', timestamp: new Date().toISOString() });
});
 
// 根据账号获取用户成绩信息
router.get('/person_exam_scores/:account', async (req, res) => {
  try {
    const examine_person_scores = await examine_scores_Model.getUser_scores(req.params.account);
    if (!examine_person_scores) return res.status(404).send('查无此用户');
    for(let i=0;i<examine_person_scores.length;i++){
      // console.log('全部用户时间数据：',examine_person_scores[i].exam_date)
      const date = new Date(examine_person_scores[i].exam_date);
      const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
      examine_person_scores[i].exam_date = formattedDate
      // console.log('全部用户时间数据：',examine_scores[i].exam_date)
    }
    res.json(examine_person_scores);
  } catch (err) {
    console.error(err);
    res.status(500).send('获取个人成绩信息错误-Error');
  }
});


// 获取所有用户做题量数据信息 getUser_scores_num_date
router.get('/user_question_stats', async (req, res) => {
  try {
    // 获取当前日期，年-月-日
    // Today_start_date,
    // Today_end_date,
    // week_start_date,
    // week_end_date,
    // month_start_date,
    // month_end_date
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    // const hour = String(now.getHours()).padStart(2, '0');
    // const minute = String(now.getMinutes()).padStart(2, '0');
    // console.log(year,month,day,hour,minute)
    //获取当前月份天数
    const month_days = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
    // console.log('当前月份天数：',month_days)
    //计算当前周的周一和周日日期
    // const week_start_day = now.getDay() === 0 ? 1 : now.getDate() - (now.getDay() - 1);
    // const week_end_day = week_start_day + 6;
    const dayOfWeek = now.getDay();
    const startOfWeek = new Date(now);
    // 计算周一的日期（周一为每周的第一天）
    const diffToMonday = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
    startOfWeek.setDate(now.getDate() + diffToMonday);
    startOfWeek.setHours(0, 0, 0, 0);
    // 计算周日的日期
    const endOfWeek = new Date(startOfWeek);
    endOfWeek.setDate(startOfWeek.getDate() + 6);
    endOfWeek.setHours(23, 59, 59, 999);
    // 使用本地时间格式化，避免时区问题
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    const week_start = formatDate(startOfWeek);
    const week_end = formatDate(endOfWeek);

    // const week_start = startOfWeek.toISOString().split('T')[0]
    // const week_end = endOfWeek.toISOString().split('T')[0]
    // const week_start_day = startOfWeek.getDate()
    // const week_end_day = endOfWeek.getDate()
    // console.log('周一日期:', week_start);
    // console.log('周日日期:', week_end);
    // console.log('周一日期号:', week_start_day);
    // console.log('周日日期号:', week_end_day);
    // console.log('当前周的周一日期：',week_start_day)
    // console.log('当前周的周日日期：',week_end_day)

    const Today_start_date = `${year}-${month}-${day} 00:00:00`;
    const Today_end_date = `${year}-${month}-${day} 23:59:59`;
    const week_start_date = `${week_start} 00:00:00`;
    const week_end_date = `${week_end} 23:59:59`;
    const month_start_date = `${year}-${month}-01 00:00:00`;
    const month_end_date = `${year}-${month}-${month_days} 23:59:59`;

    console.log('今日开始时间：',Today_start_date)
    console.log('今日结束时间：',Today_end_date)
    console.log('本周开始时间：',week_start_date)
    console.log('本周结束时间：',week_end_date)
    console.log('本月开始时间：',month_start_date)
    console.log('本月结束时间：',month_end_date)

    const stats = await examine_scores_Model.getUser_scores_num_date(
      Today_start_date,Today_end_date,
      week_start_date,week_end_date,
      month_start_date,month_end_date);
    res.json(stats); // 返回 JSON 格式的视图数据
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '未找到存储过程' });
  }
});



// 上传成绩数据 - 使用POST请求
router.post('/update_exam_score', async (req, res) => {
    try {
        const scoreData = req.body;
        // console.log('请求体',scoreData)
        // 调用模型方法上传成绩
        const result = await examine_scores_Model.update_User_scores(scoreData);
        // 返回成功响应
        res.json({
            success: true,
            message: '成绩上传成功',
            data: result
        });
    } catch (err) {
        console.error('上传成绩错误:', err);
        res.status(500).json({
            success: false,
            message: '上传个人成绩信息错误',
            error: err.message
        });
    }
});
 
module.exports = router;